<?php

namespace app\admin\controller;

use app\common\model\Brand;
use app\common\model\Category;
use app\common\model\Type;
use houdunwang\arr\Arr;
use think\Controller;
use app\common\model\Goods as GoodsModel;

/**
 *  Goods
 *  商品 admin.controller.Goods
 * Class goods
 * @package app\admin\controller
 */
class Goods extends Common
{
    protected $db;
    protected $cate;//分类数据
    //模型初始化
    protected function _initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::_initialize();
        // TODO: Change the autogenerated stub   //TODO:自定义的初始化
        $this->db = new GoodsModel();

        $this->cate = (new Category())->lists();
    }

    //商品首页
    public function lists()
    {
        $goods = $this->db->lists();
        $this->assign('goods',$goods);
        //加载模板
        return $this->fetch('lists');
    }

    //商品添加
    public function add()
    {
        if (request()->isPost()) {
            $_POST[ 'time' ] = date('Y-m-d',time());//时间戳
            $_POST['ggpic'] =  implode('|',$_POST['ggpic']);//添加商品图册
//            p($_POST);die;
            $res = $this->db->add($_POST);
            if ($res['valid']) {
                //操作成功
                $this->success($res['msg'], 'lists');
                exit;
            } else {
                $this->error($res['msg']);
                exit;
            }
        }else{
            $cateList = (new Category())->lists();//分配 分类树型数据
            $brandList = (new Brand())->lists(); //分配品牌数据
            $this->assign('brandList',$brandList);
            $this->assign('cateList',$cateList);

            return $this->fetch('add');
        }
    }

    //商品编辑
    public function edit()
    {
        //表单提交之后的操作
        if (request()->isPost()) {
            //p($_POST);die;
            //将post数据传入模型中操作
            $res = $this->db->edit(input('post.'));
            if ($res['valid']) {
                //执行成功
                $this->success($res['msg'], 'admin/goods/lists');
                exit;
            } else {
                $this->error($res['msg']);
                exit;
            }
        }else{
            //变得提交之前的操作
            //接收pid
            $pid = input('param.pid');
            //获取旧数据
            $oldData = $this->db->find($pid);
//        p($oldData);die;
            $this->assign('oldData', $oldData);
            return $this->fetch('edit');
        }

    }


}
